package club.calong.sanniu.config.interceptor;

import club.calong.sanniu.http.response.Response;
import club.calong.sanniu.util.CacheUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class AuthenticationInterceptor implements HandlerInterceptor {

    /**
     * 在到达controller之前拦截请求
     *
     * @param request  请求
     * @param response 响应
     * @param handler  头
     * @return false 不放行 , true 放行
     * @throws Exception 异常
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            return true;
        }

        String username = request.getHeader("username");
        String token = request.getHeader("X-Token");

        if (username != null && token != null) {
            if (!username.isEmpty() && !token.isEmpty()) {
                String cacheUsername = CacheUtils.getCache().get(token);
                if (cacheUsername != null) {
                    return username.equals(cacheUsername);
                }
                returnJson(response, 603, "请求头参数有误");
                return false;
            }
            returnJson(response, 602, "请求参数有空");
            return false;
        }
        returnJson(response, 601, "请求头缺少参数");
        return false;
    }

    private void returnJson(HttpServletResponse response, Integer code, String message) throws IOException {
        response.setContentType("application/json;charset=utf-8");
        PrintWriter pw = response.getWriter();

        pw.write(new ObjectMapper().writeValueAsString(new Response(code, message, null)));
        pw.flush();
        pw.close();
    }
}
